﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ERP_RORZE_DLL.Product.DAO;
using ERP_RORZE_DLL.Product.database;
using System.Text.RegularExpressions;
using ERP_RORZE_SYSTEM;

namespace ERP_RORZE_PRODUCT.Product.WTS
{
    public partial class frm_LaborWTSInput : DevExpress.XtraEditors.XtraForm
    {
        //Không dùng form này
        DataTable dt;
        ClsWTSDAO clsWTSDAO = new ClsWTSDAO();
        ClsLaborWTSTable b = new ClsLaborWTSTable();
        DataTable dtStaff = new DataTable();
        DataTable dtMoNo = new DataTable();
        private bool flagLoadDone;
        //private ctrlLaborWTSDetail laborWts;
        public event EventHandler Reload;
        private bool dropDown;

        int InputedOK;
        int InputedNG;
        int MOQty;
        int MachieNG;

        INISettings mySetting = new INISettings();
        private SqlConnection myConnection;
        private DataTable dataTable;
        AutoCompleteStringCollection itemMachine = new AutoCompleteStringCollection();
        AutoCompleteStringCollection itemStaff = new AutoCompleteStringCollection();
        AutoCompleteStringCollection itemMoNo = new AutoCompleteStringCollection();
        AutoCompleteStringCollection itemOption = new AutoCompleteStringCollection();
        AutoCompleteStringCollection itemWork = new AutoCompleteStringCollection();

        public frm_LaborWTSInput()
        {
            InitializeComponent();
            myConnection = new SqlConnection(mySetting.SQLConnectionString);
            this.txtTime.LostFocus += txtTime_LostFocus;
        }

        void txtTime_LostFocus(object sender, EventArgs e)
        {
            if (cbStaff.Text == "")
            {
                MessageBox.Show("Chưa nhập Staff ID");
                cbStaff.Focus();
            }
            if (IsNumber(txtTime.Text) == false)
            {
                MessageBox.Show("Time phải là kiểu số");
                txtTime.Focus();
                txtTime.Text = "0";
            }
            else
            {
                int Inputed = 0;
                int Total = 0;
                int OverTime = 0;
                dt = clsWTSDAO.GetAllLaborWTSStaff(cbStaff.SelectedValue.ToString(), dateDate.Value.Day, dateDate.Value.Month, dateDate.Value.Year);
                foreach (DataRow r in dt.Rows)
                {
                    Inputed = Inputed + int.Parse(r["SumofTime"].ToString());
                }
                Total = Inputed + int.Parse(txtTime.Text);
                DataTable dt2;
                dt2 = clsWTSDAO.GetAllLaborWTOverTimeStaff(cbStaff.SelectedValue.ToString(), dateDate.Value.Day, dateDate.Value.Month, dateDate.Value.Year);
                foreach (DataRow r in dt2.Rows)
                {
                    OverTime = int.Parse(r["SumofTime"].ToString());
                }
                txtTotalTime.Text =""+ Total;
                txtInputedTime.Text =""+ Inputed;
                txtOvertime.Text =""+ OverTime;
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void frm_LaborWTSInput_Load(object sender, EventArgs e)
        {
            //list Shift
            DataTable dtShift = new DataTable();
            dtShift.Columns.Add("Display");
            dtShift.Columns.Add("Value");
            for (int i = 0; i < 4; i++)
            {
                DataRow rShift = dtShift.NewRow();
                rShift["Display"] = i.ToString();
                rShift["Value"] = "T" + i.ToString();
                dtShift.Rows.Add(rShift);
            }
            cbShift.DataSource = dtShift;
            cbShift.DisplayMember = "Display";
            cbShift.ValueMember = "Value";

            ////list machine
            DataTable dt1;
            dt1 = clsWTSDAO.GetAllLMachine();
            DataRow r = dt1.NewRow();
            r["MachineID"] = "";


            dt1.Rows.InsertAt(r, 0);
            cbMachine.DataSource = dt1;
            cbMachine.DisplayMember = "MachineID";
            cbMachine.ValueMember = "MachineID";

            //list MO Number
            //DataTable dtMoNo;
            dtMoNo = clsWTSDAO.GetAllLWTSMONo();
            DataRow r1 = dtMoNo.NewRow();
            r1["MONo"] = "";
            r1["MONo"] = "";
            dtMoNo.Rows.InsertAt(r1, 0);
            cbMONo.DataSource = dtMoNo;
            cbMONo.DisplayMember = "MONo";
            cbMONo.ValueMember = "MONo";

            //dtMoNo = dt2;


            ////list MO Number
            //DataTable dt2;
            //dt2 = clsWTSDAO.GetAllLWTSMONo();
            //DataRow r1 = dt2.NewRow();
            //r1["MONo"] = "";
            //r1["FullName"] = "";
            //dt2.Rows.InsertAt(r1, 0);
            //cbMONo.DataSource = dt2;
            //cbMONo.DisplayMember = "FullName";
            //cbMONo.ValueMember = "MONo";

            

            ////list staff
            //DataTable dt4;
            //dt4 = clsWTSDAO.GetAllStaff();
            //DataRow r3 = dt4.NewRow();
            //r3["StaffID"] = "";
            //r3["FullName"] = "";
            //dt4.Rows.InsertAt(r3, 0);
            //cbStaff.DataSource = dt4;
            //cbStaff.DisplayMember = "FullName";
            //cbStaff.ValueMember = "StaffID";

            //list staff
            //DataTable dt;
            dtStaff = clsWTSDAO.GetAllStaff();
            DataRow r3 = dtStaff.NewRow();
            r3["StaffID"] = "";
            r3["StaffID"] = "";
            dtStaff.Rows.InsertAt(r3, 0);
            cbStaff.DataSource = dtStaff;
            cbStaff.DisplayMember = "StaffID";
            cbStaff.ValueMember = "StaffID";

            //dtStaff = dt4;


            ////list work
            DataTable dt5;
            dt5 = clsWTSDAO.GetAllWorkLWTS();
            DataRow r4 = dt5.NewRow();
            r4["WorkID"] = "";

            dt5.Rows.InsertAt(r4, 0);
            cbWorkID.DataSource = dt5;
            cbWorkID.DisplayMember = "WorkID";
            cbWorkID.ValueMember = "WorkID";

            dateDate.Focus();
            flagLoadDone = true;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            //kiem tra so luong ok,ng da duoc nhap
            dt = clsWTSDAO.CheckInputVlaborOPT(cbMONo.SelectedValue.ToString(), cbOption.Text);
            InputedOK = 0;
            InputedNG = 0;
            foreach (DataRow r in dt.Rows)
            {
                InputedOK = InputedOK + int.Parse(r["LaborOPTOKQty"].ToString());
                InputedNG = InputedNG + int.Parse(r["LaborOPTNGQty"].ToString());
            }
            //kiem tra so luong MOQty
            dt = clsWTSDAO.CheckMOQty(cbMONo.SelectedValue.ToString());
            MOQty = 0;
            foreach (DataRow r in dt.Rows)
            {
                MOQty = MOQty + int.Parse(r["MOQty"].ToString());
            }
            //So luong san pham gia cong ngoai may
            dt = clsWTSDAO.ChekMachineNG(cbMONo.SelectedValue.ToString());
            MachieNG = 0;
            foreach (DataRow r in dt.Rows)
            {
                MachieNG = MachieNG + int.Parse(r["SumofNG"].ToString());
            }

            //kiem tra xem nguyen cong ngay co trong MOOption khong
            dt = clsWTSDAO.CheckMOOption(cbMONo.SelectedValue.ToString(), cbOption.Text);
            int i = 0;
            foreach (DataRow r in dt.Rows)
            {
                i++;
            }
            if (i == 0)
            {
                MessageBox.Show("Không có dữ liệu trong MOOPtion");
            }
            else if (IsNumber(txtOKQty.Text) == false)
            {
                MessageBox.Show("OKQty phải là kiểu số");
            }
            else if (IsNumber(txtNGQty.Text) == false)
            {
                MessageBox.Show("NGOK phải là kiểu số");
            }
            else if (IsNumber(txtTime.Text) == false)
            {
                MessageBox.Show("Time phải là kiểu số");
            }
            else if (IsNumber(txtClampTime.Text) == false)
            {
                MessageBox.Show("ClampTime phải là kiểu số");
            }
            else if (IsNumber(txtProTime.Text) == false)
            {
                MessageBox.Show("ProTime phải là kiểu số");
            }
            else
            {
                try
                {
                    if ((InputedOK + int.Parse(txtOKQty.Text)) > (MOQty - MachieNG))
                    {
                        MessageBox.Show("Số lượng sản phẩm OK ngoài machine chỉ có: " + (MOQty - MachieNG) + ", số lượng đã nhập trước đó: " + InputedOK + " số lượng trên form: " + int.Parse(txtOKQty.Text));
                    }
                    else if ((InputedNG + int.Parse(txtNGQty.Text)) > MachieNG)
                    {
                        MessageBox.Show("Số lượng sản phẩm NG ngoài machine có: " + MachieNG + ", số lượng NG nhập trước đó là: " + InputedNG + ", số lượng NG nhập trên form là: " + int.Parse(txtNGQty.Text));
                    }
                    else
                    {
                        if ((InputedNG + InputedOK + int.Parse(txtNGQty.Text) + int.Parse(txtOKQty.Text)) == MOQty)
                        {
                            ClsMOOptionTable c = new ClsMOOptionTable();
                            c.MONo = cbMONo.SelectedValue.ToString();
                            c.OptionID = cbOption.SelectedValue.ToString();
                            c.Finishdate = dateDate.Value;
                            c.Shift = cbShift.Text;
                            clsWTSDAO.UpdateFinishMOOption(c);
                            //MessageBox.Show("Đã update vào MOOption thành công");
                        }
                        b.Clamptime = float.Parse(txtClampTime.Text);
                        b.Date = dateDate.Value;
                        b.MachineID = cbMachine.SelectedValue.ToString();
                        b.MONo = cbMONo.SelectedValue.ToString();
                        b.NGQty = int.Parse(txtNGQty.Text);
                        b.Note1 = txtNote1.Text;
                        b.Note2 = txtNote2.Text;
                        b.OKQty = int.Parse(txtOKQty.Text);
                        b.OptionID = cbOption.SelectedValue.ToString();
                        b.ProTime = float.Parse(txtProTime.Text);
                        b.Shift = cbShift.SelectedValue.ToString();
                        b.StaffID = cbStaff.SelectedValue.ToString();
                        b.Time = float.Parse(txtTime.Text);
                        b.WorkID = cbWorkID.SelectedValue.ToString();
                        clsWTSDAO.InsertLaborWTS(b);
                        MessageBox.Show("Đã nhập dữ liệu xong");
                        //this.laborWts.BindReload();
                        cbMONo.SelectedIndex = 0;
                        cbOption.SelectedIndex = 0;
                        cbWorkID.SelectedIndex = 0;
                        txtInputedTime.Text = "0";
                        txtNGQty.Text = "0";
                        txtNote1.Text = "";
                        txtNote2.Text = "";
                        txtOKQty.Text = "0";
                        txtOvertime.Text = "0";
                        txtProTime.Text = "0";
                        txtClampTime.Text = "0";
                        txtTime.Text = "0";
                        txtTotalTime.Text = "0";
                        cbMONo.Focus();

                    }
                }
                catch
                {
                    MessageBox.Show("Time, ClampTime, NGQty, OKQty, ProTime phải là kiểu số");
                }
            }
            //MessageBox.Show(""+InputedOK  +","+ InputedNG +","+MOQty +","+MachieNG);
        }

        public bool IsNumber(string pText)
        {
            Regex regex = new Regex(@"^[-+]?[0-9]*\.?[0-9]+$");
            return regex.IsMatch(pText);
        }
        
        protected override bool ProcessKeyPreview(ref Message m)
        {
            if (m.Msg == 0x0100 && (int)m.WParam == 13)
            {
                this.ProcessTabKey(true);
            }
            return base.ProcessKeyPreview(ref m);
        }

        private void frm_LaborWTSInput_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Alt)
            {
                if (e.KeyCode == Keys.D)
                {
                    this.btnAdd.PerformClick();
                }
            }
            else if (e.KeyCode == Keys.End)
            {
                btnAdd.Focus();
            }
            else if (e.KeyCode == Keys.Home)
            {
                dateDate.Focus();
            }
        }

        private void cbMONo_SelectedIndexChanged(object sender, EventArgs e){
            if (flagLoadDone)
            {
                DataTable dt3;
                dt3 = clsWTSDAO.GetAllLOptionID(cbMONo.SelectedValue.ToString());
                DataRow r2 = dt3.NewRow();
                r2["OptionID"] = "";

                dt3.Rows.InsertAt(r2, 0);
                cbOption.DataSource = dt3;
                cbOption.DisplayMember = "OptionID";
                cbOption.ValueMember = "OptionID";

                if (dtMoNo.Rows.Count > 0)
                {
                    DataRow[] row = dtMoNo.Select("MONo ='" + cbMONo.SelectedValue.ToString() + "'");
                    lblPartNo.Text = row[0]["PartID"].ToString();
                }
                else
                {
                    lblPartNo.Text = String.Empty;
                }
            }
        }

        private void cbStaff_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (flagLoadDone && dtStaff.Rows.Count > 0)
            {
                DataRow[] row = dtStaff.Select("StaffID ='" + cbStaff.SelectedValue.ToString() + "'");
                lblStaffName.Text = row[0]["StaffName"].ToString();
            }
        }

        private void txtNote2_MouseDown(object sender, MouseEventArgs e)
        {
            ((TextBox)sender).SelectAll();
        }

        private void txtNote2_Enter(object sender, EventArgs e)
        {
            ((TextBox)sender).SelectAll();
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            // Add controls for which Arrow keys => focus is not required.
            if ((!dropDown && (ActiveControl is TextBox || ActiveControl is System.Windows.Forms.ComboBox || ActiveControl is System.Windows.Forms.DateTimePicker)))
            {
                switch (keyData)
                {
                    case Keys.Up:
                    //case Keys.Down:

                        //bool forward = (keyData == Keys.Down);
                        if (this.ProcessTabKey(false))
                        {
                            return true;
                        }

                        break;
                }
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void cbShift_DropDown(object sender, EventArgs e)
        {
            dropDown = true;
        }

        private void cbShift_DropDownClosed(object sender, EventArgs e)
        {
            dropDown = false;
        }

        private void lblStaffName_MouseDown(object sender, MouseEventArgs e)
        {
            ((TextBox)sender).SelectAll();
        }

        private void BindDataMachine()
        {
            SqlCommand cmd_sql = myConnection.CreateCommand();
            cmd_sql.CommandText = "SELECT [222_Machine].MachineID FROM [222_Machine]";
            SqlDataReader dataReader = cmd_sql.ExecuteReader();
            while (dataReader.Read())
            {
                itemMachine.Add(dataReader["MachineID"].ToString());
            }
            cbMachine.AutoCompleteCustomSource = itemMachine;

            dataReader.Close();
            cmd_sql.Dispose();
        }

        private void BindDataStaff()
        {
            SqlCommand cmd_sql = myConnection.CreateCommand();
            cmd_sql.CommandText = "SELECT [222_Staff].StaffID FROM [222_Staff]";
            SqlDataReader dataReader = cmd_sql.ExecuteReader();
            while (dataReader.Read())
            {
                itemStaff.Add(dataReader["StaffID"].ToString());
            }
            cbStaff.AutoCompleteCustomSource = itemStaff;

            dataReader.Close();
            cmd_sql.Dispose();
        }

        private void BindDataMoNo()
        {
            SqlCommand cmd_sql = myConnection.CreateCommand();
            cmd_sql.CommandText = "SELECT [242_MO].MONo FROM [242_MO]";
            SqlDataReader dataReader = cmd_sql.ExecuteReader();
            while (dataReader.Read())
            {
                itemMoNo.Add(dataReader["MONo"].ToString());
            }
            cbMONo.AutoCompleteCustomSource = itemMoNo;

            dataReader.Close();
            cmd_sql.Dispose();
        }

        private void BindDataWork()
        {
            SqlCommand cmd_sql = myConnection.CreateCommand();
            cmd_sql.CommandText = "SELECT [242_Work].WorkID FROM [242_Work]";
            SqlDataReader dataReader = cmd_sql.ExecuteReader();
            while (dataReader.Read())
            {
                itemWork.Add(dataReader["WorkID"].ToString());
            }
            cbWorkID.AutoCompleteCustomSource = itemWork;

            dataReader.Close();
            cmd_sql.Dispose();
        }
    }
}